import { Drawer, Button, message } from 'antd';
import {SystemResourceTree} from '@/components/system/resource'
import {useEffect, useState} from 'react';
import { authRole, listRoleAcl } from '@/services/system/acl';

const SystemRoleAuth = (props) => {
  const { visible, onClose, values } = props;
  const [resourceIdList, handleResourceId] = useState([]);

  useEffect( () => {
    const lostData = async () => {
      const response = await listRoleAcl(values.id);
      const listData = Array.isArray(response.data) ? response.data : [];

      return listData;
    };

    lostData().then((listData) => {
      handleResourceId(listData);
    });
  }, []);

  const handleAuth = async () => {
    const data = await authRole({
      principalId: values.id,
      resourceIdList
    });

    if (data.success) {
      message.success('角色授权成功!');
      onClose();
    } else {
      message.error('角色授权失败!');
    }
  }

  return (
    <Drawer
        title={values? values.name + ' 角色授权' : '角色授权'}
        placement="right"
        visible={visible}
        onClose={onClose}
        width={350}
        footer={
          <Button type="primary" block onClick={() => handleAuth()}> 授 &nbsp;&nbsp;&nbsp;&nbsp; 权 </Button>
        }
      >
        <SystemResourceTree 
          resourceIdList={resourceIdList} 
          checkResourceIdList={handleResourceId}
        />
      </Drawer>
  );
}

export default SystemRoleAuth;